package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ListView;
import com.android.volley.VolleyError;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.FileAdapter;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.FileListParams;
import com.isunland.managesystem.entity.companymemorabiliazi;
import com.isunland.managesystem.entity.companymemorabiliaziListOriginal;
import com.isunland.managesystem.utils.FUtils;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/5/3 13:38
 */
public class FileListFragment extends BaseListFragment implements FileAdapter.Callback {
  //private static final int MENU_ITEM_ADD_FILE = 1;
  private static final int REQUEST_SELECT_FILE = 2;
  private static final int REQUEST_UPLOAD = 3;
  private FileListParams mParams;
  private FileAdapter mAdapter;
  private ArrayList<companymemorabiliazi> mList;
  private String mId;
  private FUtils mFutils;

  @Override public void initData() {
    super.initData();
    mParams =
        mBaseParams instanceof FileListParams ? (FileListParams) mBaseParams : new FileListParams();
    mList = new ArrayList<>();
    mAdapter = new FileAdapter(mActivity, mList, this);
    mFutils = new FUtils();
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    setTitleCustom(R.string.relatedFile);
    setListAdapter(mAdapter);
    final View fabBgView = view.findViewById(R.id.fab_bg);
    final FloatingActionMenu floatingActionButton =
        (FloatingActionMenu) view.findViewById(R.id.fam_menu);

    fabBgView.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        floatingActionButton.close(true);
      }
    });
    //floatingActionButton.setMenuButtonColorNormal(Color.parseColor(BaseActivity.accentSkin));
    //floatingActionButton.setMenuButtonColorPressed(fabSkinPressed);

    floatingActionButton.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() {
      @Override public void onMenuToggle(boolean b) {
        mFutils.revealShow(fabBgView, b);
      }
    });

    FloatingActionButton fabNewFile = (FloatingActionButton) view.findViewById(R.id.menu_new_file);
    //fabNewFile.setColorNormal(folderskin);
    //fabNewFile.setColorPressed(fabskinpressed);
    fabNewFile.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        //mainActivityHelper.add(MainActivityHelper.NEW_FILE);
        //utils.revealShow(fabBgView, false);
        selectFile();
        floatingActionButton.close(true);
      }
    });
  }

  @Override public String getUrl() {
    return ApiConst.URL_QUERY_LIST_COMPANYMEMORABILIAZI;
  }

  @Override public HashMap<String, String> getparameters() {
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("mainId", mParams.getMainId());
    return params.getParams();
  }

  @Override public void resolveResponse(String json) {
    companymemorabiliaziListOriginal original =
        new Gson().fromJson(json, companymemorabiliaziListOriginal.class);
    mList.clear();
    mList.addAll(original.getRows());
    mAdapter.notifyDataSetChanged();
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    companymemorabiliazi item = mAdapter.getItem(position - mListview.getHeaderViewsCount());
    downloadOrCheck(item);
  }

  private void downloadOrCheck(companymemorabiliazi item) {
    if (item == null || TextUtils.isEmpty(item.getSdefpropValue())) return;
    showDialog(ExtraDownLoadDialogFragment.newInstance("", item.getSdefpropValue()), 0);
  }

  //@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
  //  super.onCreateOptionsMenu(menu, inflater);
  //  menu.add(0, MENU_ITEM_ADD_FILE, 0, getString(R.string.addFile));
  //}

  //@Override public boolean onOptionsItemSelected(MenuItem item) {
  //
  //  switch (item.getItemId()) {
  //    case MENU_ITEM_ADD_FILE:
  //      selectFile();
  //      return true;
  //    default:
  //      return super.onOptionsItemSelected(item);
  //  }
  //}

  private void selectFile() {
    Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
    intent2.setType("*/*");
    intent2.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(Intent.createChooser(intent2, getString(R.string.chooseFileExplorer)),
        REQUEST_SELECT_FILE);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_SELECT_FILE && data != null) {
      String path = FileUtil.getPath(getActivity(), data.getData());
      if (TextUtils.isEmpty(path)) return;
      mId = UUID.randomUUID().toString();
      showDialog(FileUploadDialgFragment.newInstance(path, mId, "plot_mapping_information"),
          REQUEST_UPLOAD);
    }
    if (requestCode == REQUEST_UPLOAD) {
      volleyPostAddFile(data.getStringExtra(FileUploadDialgFragment.EXTRA_PATH));
    }
  }

  private void volleyPostAddFile(String filePath) {
    if (TextUtils.isEmpty(filePath)) return;
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_UPDATE_COMPANYMEMORABILIAZI);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mId);
    params.put("mainId", mParams.getMainId());
    params.put("sdefpropValue", filePath);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failure_operation);
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        Base result = new Gson().fromJson(json, Base.class);
        ToastUtil.show(result.getMessage());
        if (Base.SUCCESS == result.getResult()) {
          volleyPost();
        }
      }
    });
  }

  @Override public void delete(companymemorabiliazi item) {
    if (item == null || item.getId() == null) return;
    volleyPostDelete(item.getId());
  }

  @Override public void check(companymemorabiliazi item) {
    downloadOrCheck(item);
  }

  private void volleyPostDelete(String id) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELETE_COMPANYMEMORABILIAZI);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", id);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failure_operation);
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        Base result = new Gson().fromJson(json, Base.class);
        ToastUtil.show(result.getMessage());
        if (Base.SUCCESS == result.getResult()) {
          volleyPost();
        }
      }
    });
  }

  @Override protected int setCustomLayoutId() {
    return R.layout.fragment_list_file;
  }

  @Override protected int setCustomtListViewId() {
    return R.id.lv_pullToRefresh;
  }
}
